import React from 'react';
import { View, Text, FlatList, Image, TouchableOpacity } from 'react-native';
import Sound from 'react-native-sound';
const styles = StyleSheet.create({
  img: {
    width: 20,
    height: 20,
  },
  talk: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 5,
  },
  text: {
    fontSize: 18,
  },
});

function TextMessage(props) {
  return (
    <View style={styles.talk}>
      <Text style={styles.text}>{props.context}</Text>
    </View>
  );
}

function AudioMessage({ from, url }) {
  function playAudio() {
    let sound = new Sound(url, '', (err) => {
      if (err) {
        console.log('failed to load the sound', err);
        return;
      }
      sound.play((success) => {
        if (success) {
          console.log('successfully finished playing');
        } else {
          console.log('playback failed due to audio decoding errors');
        }
      });
    });
  }
  return (
    <View style={styles.talk}>
      <Text style={[styles.text, styles.user]}>{`${from}: `}</Text>
      <TouchableOpacity onPressIn={playAudio}>
        <Image style={styles.img} source={require('../img/talk.png')} />
      </TouchableOpacity>
    </View>
  );
}

function Messages({ messages }) {
  return (
    <View>
      <FlatList
        data={messages}
        renderItem={({ item, index }) => {
          const msg = item;
          if (msg.type === 'text') {
            let { from, text } = msg;
            return <TextMessage from={from} context={text} key={text + index} />;
          } else {
            let { from, file } = msg;
            return <AudioMessage from={from} url={file.url} key={file.url + index} />;
          }
        }}
      />
    </View>
  );
}
export default Messages;

